package com.aaa.jwt;

import io.jsonwebtoken.*;
import org.springframework.security.core.Authentication;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTokenUtils {
    private static final String ISS="aaa";// jwt签发者
    private static final long EXP=1000*60*60L;// jwt的过期时间，默认1个小时
    private static final String SECRET="JAVA";// 密钥


    public static String getToken(Authentication authentication){
        HashMap<String,Object> claims=new HashMap<>();
        claims.put("auth",authentication);

        JwtBuilder builder = Jwts.builder()
                //发布者
                .setIssuer(ISS)
                //加密方式,密钥
                .signWith(SignatureAlgorithm.HS512, SECRET)
                //超时时间
                .setExpiration(new Date(System.currentTimeMillis() + EXP))
                //发布时间
                .setIssuedAt(new Date());
        String token=builder.addClaims(claims).compact();

        return token;
    }
    public static Claims getToken(String token){
        Jws<Claims> jws=Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        return jws.getBody();
    }

    /**
     * 判断token是否过期
     * @param claims
     * @return
     */
    public static boolean isExpiration(Claims claims){
        Date expiration=claims.getExpiration();
        Date now=new Date();
        if(now.getTime()-expiration.getTime()>0){
            return false;
        }else {
            return true;
        }
    }
    public static Map getAuth(Claims claims){
        Map auth= (Map) claims.get("auth");
        return auth;
    }
}
